<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/1/26
 * Time: 10:53
 * Desc: index - old
 */
namespace app\index\controller;

use controller\BasicWechat;
use app\comm\service\SendMsgService;
use app\comm\service\UserService;
use app\comm\service\UserOrderService;
use think\Controller;
use think\Loader;
use think\Db;
use app\comm\controller\WebLogController;

use think\Request;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\LabelAlignment;
use Endroid\QrCode\QrCode;
use Symfony\Component\HttpFoundation\Response;
//const LABEL_FONT_PATH_DEFAULT = '';   //生成二维码
class User_old extends WebLogController {

    public function index1(){
        $qrCode = new QrCode('Life is too short to be generating QR codes');
        header('Content-Type: '.$qrCode->getContentType());
        echo $qrCode->writeString();
    }
    /**
     * 个人会员的首页
     * @return [type] [description]
     */
    public function index(){
        $UserService = new UserOrderService;
        return view('user/index',['info'=>$this->userinfo]);
    }

    /**
     * 我的地址列表
     */
    public function addreslist(){
        $userservice = new UserService();
        $list = $userservice ->dresslist($this->userinfo['uid']);
        return view('user/dresslist',['dresslist'=> $list]);
    }

    /**
     * ajax获取地址列表
     */
    public function ajaxaddreslist(){
        $uid = $this->userinfo['uid'];
        $map['uid']        = ['eq',$uid];
        //$map['is_default'] = ['eq',1];
        $useaddreslist = Db::table("ys_user_address")->where($map)->select();
        if(!empty($useaddreslist)){
            return json(["status"=>1,"data"=>$useaddreslist]);
        }
        return json(["status"=>0,"data"=>0]);
    }

    /**
     * 用户余额改变充值变更，有连个方法，一个是增加一个是减少
     */
    public function userwalletadd(){
        $data = [
            'uid'   => $this->userinfo['uid'],
            'point' => 5,
            'uname' => 'yaopeng',
            'chargetype' => 1,
            'charge_cn' => "买套少一毛",
        ];
        $userservice = new UserService();
        $list = $userservice ->userwalletdesc($data);
    }

    /**
     * 保存地址
     * @return [type] [view]
     */
    public function savedizhi(){
        if($post = input('post.')){
            $post["province"]	= $post["province"];
            $post["city"]		= $post["city"];
            $post["area"]		= $post["area"];
            $userservice = new UserService();
            $res = $userservice ->saveaddress($post);
            if($res){
                $this->redirect('user/addreslist');
            }
        }
        return view('user/saveaddress');
    }

    /**
     * 编辑地址
     */
    public function editordress(Request $request){
        $id = request()->get("id");
        $userservice = new UserService();
        if($request->isPost()){
            $post = $this->request->post();
            $userservice->edtiordress($post);
            return $this->redirect('user/addreslist');
        }
        $dres = $userservice ->getonedress($id);
        return view('user/editordress',['dress'=>$dres]);
    }

    /**
     * 删除地址
     */
    public function deleteaddress(){
        $id = input('get.id');
        $userservice = new UserService();
        $res = $userservice ->deletedress($id);
        $this->redirect('user/addreslist');
    }

    /**
     * 默认地址
     */
    public function setdefaultdress(Request $request){
        $uid =$request ->get("uid");
        $id  =$request  ->get("id");
        $userservice = new UserService();
        $userservice->serdefauledress($id,$uid);
        return json(["status"=>1,"msg"=>"成功设置"]);
    }

    /**
     * 修改密码
     */
    public function savepassword(){
        if(request()->isPost()){
            $post = input('post.');
            $user = db('user')->where('mobile',$post['mobile'])->find();
            $reg = "/^[0-9a-zA-Z_]{6,16}$/";
            if(!preg_match($reg,$post['password'])){
                $this->error('密码格式不正确，只能是字母数字下划线6~16位组合','');
            }
            if($post['password'] != $post['repassword']){
                $this->error('两次密码输入不一致，请重新填写','');
            }
            if($user['verify_code'] != $post['verify_code']){
                $this->error('验证码输入不正确','');
            }
            if($user['send_time']+3600<time()){
                $this->error('验证码已过期，请重新再试','');
            }
            $data['password'] = md5($post['password']);
            $result = db('user')->where('mobile',$post['mobile'])->data($data)->update();
            $result!==false?$this->success('修改成功',''):$this->error('密码修改失败，请重试','');
//			$userservice = new UserService;
//			$res = $userservice ->savepass($post);
//			switch ($res) {
//				case '1':
//					$this->success("保存成功",'user/index');
//					break;
//				case '2':
//					$this-> error('两次密码不一致');
//					break;
//				case '3':
//					$this-> error('旧密码不对');;
//					break;
//				default:
//					break;
//			}
            $this->redirect('user/index');
        }
        $uid = session('_user_uid_')['uid'];
        $where_user['uid'] = ['eq',$uid];
        $member = db('user')->where($where_user)->field('uid,realname,mobile,verify_code,send_time')->find();
        $this->assign('member',$member);
        return view('user/savepass');
    }

    /**
     * 用户优惠券
     * @return [type] [description]
     */
    public function userycar(){
        $uid = $this->userinfo['uid'];
        $userservice = new UserService;
        $res = $userservice ->getycard($uid);
        return view('user/userycar',['res'=>$res]);
    }

    /**
     * 发送短信获取验证码
     */
    public function getcord(){
        $sendmsg = new \app\comm\service\SendMsgService;
        $send = $sendmsg -> sendmsg(15588680183);
        if($send){
            return 1;
        }
        return 0;
    }

    /**
     * 生成二维码，是用户的付款码
     * @return [type] [description]
     */
    public function pay_qrade(){
        $pay_code = $this->userinfo['pay_code'];
        $qrCode=new QrCode();
        $url ='http://www.baidu.com'.$pay_code;
        $qrCode->setText($url)
            ->setSize(300)
            ->setLabelFontPath(VENDOR_PATH.'endroid\qrcode\assets\noto_sans.otf')
            //->setErrorCorrectionLevel('high')
            ->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
            ->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0))
            ->setLabelFontSize(16);
        header('Content-Type: '.$qrCode->getContentType());
        echo $qrCode->writeString();
        exit;
    }

    /**
     * 我的付款码
     */
    public function paycode(){
        return view('user/paycode');
    }

    /**
     *条形码的生成算法
     * @return [type] [description]
     */
    public function barcode_create(){
        $content=$pay_code = $this->userinfo['pay_code'];
        // 引用barcode文件夹对应的类
        Loader::import('BCode.BCGFontFile',EXTEND_PATH);
        //Loader::import('BCode.BCGColor',EXTEND_PATH);
        Loader::import('BCode.BCGDrawing',EXTEND_PATH);
        // 条形码的编码格式
        Loader::import('BCode.BCGcode39',EXTEND_PATH,'.barcode.php');
        // $code = '';
        // 加载字体大小
        //$font = new BCGFontFile('./class/font/Arial.ttf', 18);
        //颜色条形码
        $color_black = new \BCGColor(0, 0, 0);
        $color_white = new \BCGColor(255, 255, 255);
        $drawException = null;
        try
        {
            $code = new \BCGcode39();
            $code->setScale(2);
            $code->setThickness(30); // 条形码的厚度
            $code->setForegroundColor($color_black); // 条形码颜色
            $code->setBackgroundColor($color_white); // 空白间隙颜色
            // $code->setFont($font); //
            $code->parse($content); // 条形码需要的数据内容
        }
        catch(\Exception $exception)
        {
            $drawException = $exception;
        }
        //根据以上条件绘制条形码
        $drawing = new \BCGDrawing('', $color_white);
        if($drawException) {
            $drawing->drawException($drawException);
        }else{
            $drawing->setBarcode($code);
            $drawing->draw();
        }
        // 生成PNG格式的图片
        header('Content-Type: image/png');
        // header('Content-Disposition:attachment; filename="barcode.png"'); //自动下载
        $drawing->finish(\BCGDrawing::IMG_FORMAT_PNG);
    }

    /**
     * 邀请用户增加积分
     * @return [type] [description]
     */
    public function testyao(){
        $userservice = new UserService;
        $res = $userservice ->addbuserpoint(11);
    }

    /**
     * 我的积分展示
     */
    public function mypoint(){
        return view('user/mypoint');
    }

    //积分排行
    public function mypointmendian(){
        return view('user/mypointmendian');
    }

    //我的积分变更记录
    public function mypointapi($page=1,$limt=10){
        //$userservice = new UserService
        //     	$type=1;
        $uid     = $this->userinfo["uid"];
        $mupoint = Db::table("ys_user_point_log")->where("uid",$uid)
            ->page($page,$limt) ->order('addtime desc')->select();
        foreach ($mupoint as $key => &$value) {
            $value["store_cn"] = Db::table("ys_store")->where($value["store_id"])->find()["title"];
        }
        return json(["status"=>1,"data"=>$mupoint]);
    }

    //我的积分排行展示api
    public function mypointmendianapi($type=2,$page=1,$limt=10){
        $userservice = new UserService;
        $res = $userservice ->stordesc($this->userinfo['uid'],$type,$page,$limt);
        return json($res);
    }

    /**
     * 积分获取方式展示
     */
    public function pointdisp(){
        return view('user/pointdisp',[]);
    }

    /**
     * 我的收藏
     */
    public function usercollect(){
        $uid = $this->userinfo['uid'];
        $list = Db::table("ys_user_collect")->where("uid",$uid )->select();
        foreach ($list as $key => &$value) {
            $value["goods"] = Db::table("ys_goods")->where("id",$value["goods_id"])->find();
        }
        $this->assign('list',$list);
        //return view('user/usercollect',['list'=>$list]);
        return json($list);
    }

    /**
     * @Author lignyun
     * @Desc    会员充值
     */
    public function recharge(){
        $user = session('_user_uid_');
        $member = Db::name('user')->where('uid',$user['uid'])->find();
        $mid = sprintf("%06d", $member['uid']);
        $order_sn = $this->getorder_sn($mid);
        $this->assign('order_sn',$order_sn);
        $this->assign('member',$member);
        return $this->fetch('recharge');
    }

    /**
     * @Author lignyun
     * @Desc    获取订单号
     */
    private function getorder_sn($mid){
        $data = date('YmdHis',time());
        for($i=0;$i<6;$i++){
            $data .= rand(0,9);
        }
        $data .= $mid;
        return $data;
    }

    /**
     * @Author  lignyun
     * @Desc    获取短信验证码
     */
    public function get_verify_code(){
        $post = input('post.');
        $where_user['mobile'] = ['eq',$post['mobile']];
        $member = db('user')->where($where_user)->find();
        if(empty($member)){
            $this->error('找不到会员信息，请重试','');
        }
        $time = time();
        if(!empty($member['send_time']) && ($member['send_time']+60>$time)){
            $this->error('请在1分钟之后重新发送短信验证','');
        }else{
            $code=rand(100000,999999);
            $response = \SMS::sendSms(
                "雨泪", // 短信签名
                "SMS_86680176", // 短信模板编号
                $post['mobile'], // 短信接收者
                Array(  // 短信模板中字段的值
                    "code"=>$code,
                )
            );
            if ($response->Code == 'OK' ) {
                $where_user['mobile'] = ['eq',$post['mobile']];
                $data_arr = [
                    'verify_code'=>$code,
                    'send_time'=>time()
                ];
                db('user')->where($where_user)->data($data_arr)->update();
                $this->success('发送成功','');
            } else {
                halt($response->Code);
                $this->error('发送失败','');
            }
        }
    }

}
